﻿using System;
using System.Web;
using System.Web.Mvc;

namespace Hr.Models
{
    public class MyJson : JsonResult
    {
        public MyJson()
        {
            JsonRequestBehavior = JsonRequestBehavior.AllowGet;
        }

        public MyJson(object data)
        {
            JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            Data = data;
        }

        private string _dateTimeFormatter = "yyyy-MM-dd";

        public string DateTimeFormatter
        {
            get { return _dateTimeFormatter; }
            set { _dateTimeFormatter = value; }
        }

        public bool ShowEnumValue { get; set; }

        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if ((this.JsonRequestBehavior == JsonRequestBehavior.DenyGet) && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException("JsonRequest_GetNotAllowed");
            }
            HttpResponseBase response = context.HttpContext.Response;
            if (!string.IsNullOrEmpty(this.ContentType))
            {
                response.ContentType = this.ContentType;
            }
            else
            {
                response.ContentType = "application/json";
            }
            if (this.ContentEncoding != null)
            {
                response.ContentEncoding = this.ContentEncoding;
            }
            if (this.Data != null)
            {
                var json = JsonHelper.SerializeObject(Data, _dateTimeFormatter, ShowEnumValue);
                response.Write(json);
            }
        }
    }
}